package com.celesea.workflow.component;

import com.alibaba.fastjson.JSON;
import com.celesea.framework.authority.AuthorityPrincipal;
import com.celesea.framework.jwt.JwtUtil;
import com.celesea.framework.util.EnvUtil;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * @author JackYuan
 * @create 2017-11-22 20:09
 */
public final class RestTemplateUtils {

    private final static class JwtRestTemplate extends RestTemplate {

        @Override
        protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
            ClientHttpRequest request = super.createRequest(url, method);
            AuthorityPrincipal user = EnvUtil.getAuthorityUser();
            String cookie = JwtUtil.JWT_TOKEN + "=" + user.getJwtToken();
            request.getHeaders().add("Cookie", cookie);
            return request;
        }
    }

    private final static class SingletonRestTemplate {
        /**
         * 单例对象实例
         */
        static final JwtRestTemplate INSTANCE = new JwtRestTemplate();
    }

    private RestTemplateUtils() {

    }

    /**
     * 单例实例
     */
    public static RestTemplate getInstance() {
        return SingletonRestTemplate.INSTANCE;
    }

    public static <T> T get(String url, Map<String, Object> uriVariables, Class<T> clazz) {
        String response = getInstance().getForObject(url, String.class, uriVariables);
        T result = JSON.parseObject(response, clazz);
        return result;
    }
}
